<?php

class Retailer_Backend_Adminhtml_SelectController extends Mage_Adminhtml_Controller_action
{

    protected function _initAction() {
            $this->loadLayout()
                    ->_setActiveMenu('backend/select')
                    ->_addBreadcrumb(Mage::helper('adminhtml')->__('Selection Manager'), Mage::helper('adminhtml')->__('Content Manager'));

            return $this;
    }

    public function indexAction() {
            $model  = Mage::getModel('backend/backend')->load(0);
            Mage::register('backend_data', $model);
            $this->loadLayout();
                    $this->_setActiveMenu('backend/select');

                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Content Manager'), Mage::helper('adminhtml')->__('Content Manager'));
                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Content News'), Mage::helper('adminhtml')->__('Content News'));

                    $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

                    $this//->_addContent($this->getLayout()->createBlock('backend/adminhtml_select'))
                            ->_addLeft($this->getLayout()->createBlock('backend/adminhtml_select_edit_tabs'));

                    $this->renderLayout();
    }

    public function editAction() {
            $id     = $this->getRequest()->getParam('id');
            $model  = Mage::getModel('backend/backend')->load($id);

            if ($model->getId() || $id == 0) {
                    $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
                    if (!empty($data)) {
                            $model->setData($data);
                    }

                    Mage::register('backend_data', $model);

                    $this->loadLayout();
                    $this->_setActiveMenu('backend/select');

                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Content Manager'), Mage::helper('adminhtml')->__('Content Manager'));
                    $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Content News'), Mage::helper('adminhtml')->__('Content News'));

                    $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

                    $this->_addContent($this->getLayout()->createBlock('backend/adminhtml_select_edit'))
                            ->_addLeft($this->getLayout()->createBlock('backend/adminhtml_select_edit_tabs'));

                    $this->renderLayout();
            } else {
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Product does not exist'));
                    $this->_redirect('*/*/');
            }
    }

    public function newAction() {
            $this->_forward('edit');
    }

    public function saveAction() {
            if ($data = $this->getRequest()->getPost()) {
                    $user = Mage::getSingleton('admin/session')->getUser();
                    $link = Mage::getModel('backend/backend')->load($data['storeID'],'user_id');
                    $model = Mage::getModel('catalog/category');//->load(2);
                    $i=array();
                    $i[0]=0;
                    if(isset($data['root'])){
                        if(isset($data['HMU'])){
                            $data['GMU']=2.3;
                            $data['GRU']=0.5;
                            $data['GOFF']=0;
                        }
                        //$price;
                        //$multi;
                        $s_array = array();
                        $base_price = array();
                        $m_array = $model->getProductCollection();
                        foreach($m_array as $mod){

                            $s_array[$i[0]] = Mage::getModel('catalog/product')->load($mod->getId());
                            $base_price[$i[0]] = $s_array[$i[0]]->getPrice();
                            $cost = $s_array[$i[0]]->getPrice();
                            $s_array[$i[0]]->setStoreId(0);
                            $i[$i[0]+1]=$s_array[$i[0]]->getId();
                            //$multi = 2.000;
                            //$price_1 = $m->getData('price');
                            $price = $s_array[$i[0]]->getPrice() * $data['GMU'];//*$multi);// * 2;//(float)$data['GMU'];
                            $roundHelp = $data['GRU'];
                            $price = (round($price/$roundHelp, 0)*$roundHelp)-$data['GOFF'];
                            //$var = $price;
                            //$price = (float)($price * 2.000);
                            $websites = $s_array[$i[0]]->getWebsiteIds();
                            array_push($websites,$link->getStoreId());
                            $s_array[$i[0]]->setWebsiteIds($websites);
                            $s_array[$i[0]]->setStoreId($link->getStoreId());
                            //$s_array[$i[0]]->setData('name',"$price");
                            $s_array[$i[0]]->setPrice($price);
                            $s_array[$i[0]]->setCost($cost);
                            $s_array[$i[0]]->save();
                            $i[0]++;
                        }
                    }
                    $trace = 0;
                    for($i = 0;$i<$data['cat'];$i++){
                        $val = $i+1;
                        if(isset($data["sub_$val"])){
                        if(isset($data['HMU'])){
                            $data["sub_MU_$val"]=2.3;
                            $data["sub_RU_$val"]=0.5;
                            $data["sub_OFF_$val"]=0;
                        }
                            $mod = Mage::getModel('catalog/category')->load($data["sub_$val"]);
                            //$s_array = array();
                            $m_array = Mage::getModel('catalog/product')->getCollection()->addCategoryFilter($mod);
                            //$trace = count($m_array);
                            $m_array = array_keys($mod->getProductsPosition());
                            //$trace = $mod->getName();
                            $count = 0;
                            foreach($m_array as $m){
                                $temp_mod = Mage::getModel('catalog/product')->load($m);
                                $cost = $temp_mod->getPrice();
                                $price = $temp_mod->getPrice() * $data["sub_MU_$val"];
                                $price = (round($price/$data["sub_RU_$val"])*$data["sub_RU_$val"])-$data["sub_OFF_$val"];
                                $websites = $temp_mod->getWebsiteIds();
                                array_push($websites,$link->getStoreId());
                                $temp_mod->setWebsiteIds($websites);
                                $temp_mod->setStoreId($link->getStoreId());
                                $temp_mod->setPrice($price);
                                $temp_mod->setCost($cost);
                                $temp_mod->save();
                                $count++;
                            }
                        }
                        for($j = 0;$j<$data["cat_$val"];$j++){
                            $val2 = $j+1;
                            if(isset($data["sub_{$val}_$val2"])){
                            if(isset($data['HMU'])){
                                $data["sub_{$val}_MU_$val2"]=2.3;
                                $data["sub_{$val}_RU_$val2"]=0.5;
                                $data["sub_{$val}_OFF_$val2"]=0;
                            }
                            
                            $mod = Mage::getModel('catalog/category')->load($data["sub_{$val}_$val2"]);
                            //$s_array = array();
                            $m_array = Mage::getModel('catalog/product')->getCollection()->addCategoryFilter($mod);
                            //$trace = count($m_array);
                            $m_array = array_keys($mod->getProductsPosition());
                            //$trace = $mod->getName();
                            $count = 0;
                            foreach($m_array as $m){
                                $temp_mod = Mage::getModel('catalog/product')->load($m);
                                $cost = $temp_mod->getPrice();

                                $price = $temp_mod->getPrice() * $data["sub_{$val}_MU_$val2"];
                                $price = (round($price/$data["sub_{$val}_RU_$val2"])*$data["sub_{$val}_RU_$val2"])-$data["sub_{$val}_OFF_$val2"];
                                $websites = $temp_mod->getWebsiteIds();
                                array_push($websites,$link->getStoreId());
                                $temp_mod->setWebsiteIds($websites);
                                $temp_mod->setStoreId($link->getStoreId());
                                $temp_mod->setPrice($price);
                                $temp_mod->setCost($cost);
                                $temp_mod->save();
                                $count++;
                            }
                            }
                        }
                    }
//                    $model2 = Mage::getModel('backend/backend');
//                    $model2->setData('user_id',$this->getRequest()->getParam('id'));
//                    $model2->setData('filename_logo',$data['filename']);
                    
                    try {
//                            if ($model->getCreatedAt() == NULL || $model->getUpdatedAt() == NULL) {
//                                    $model->setCreatedAt(now())
//                                            ->setUpdatedAt(now());
//                            } else {
//                                    $model->setUpdatedAt(now());
//                            }
//                            echo "1";
                            
                            //$link->save();
//                            echo "2";
                            $prod = Mage::getModel('catalog/product')->load(1);
                            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('backend')->__("Item was successfully saved"));
                            Mage::getSingleton('adminhtml/session')->setFormData(false);

                            if ($this->getRequest()->getParam('back')) {
                                    $this->_redirect('*/*/edit', array('id' => $model->getId()));
                                    return;
                            }
                            $this->_redirect('*/*/');
                            return;
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }
    }
    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('backend')->__('Unable to find item to save'));
    $this->_redirect('*/*/');
    }

    public function deleteAction() {
            if( $this->getRequest()->getParam('id') > 0 ) {
                    try {
                            $model = Mage::getModel('backend/backend');

                            $model->setId($this->getRequest()->getParam('id'))
                                    ->delete();

                            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
                            $this->_redirect('*/*/');
                    } catch (Exception $e) {
                            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                    }
            }
            $this->_redirect('*/*/');
    }

public function massDeleteAction() {
    $backendIds = $this->getRequest()->getParam('backend');
    if(!is_array($backendIds)) {
                    Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
    } else {
        try {
            foreach ($backendIds as $backendId) {
                $backend = Mage::getModel('backend/backend')->load($backendId);
                $backend->delete();
            }
            Mage::getSingleton('adminhtml/session')->addSuccess(
                Mage::helper('adminhtml')->__(
                    'Total of %d record(s) were successfully deleted', count($backendIds)
                )
            );
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        }
    }
    $this->_redirect('*/*/index');
}

public function massStatusAction()
{
    $backendIds = $this->getRequest()->getParam('backend');
    if(!is_array($backendIds)) {
        Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
    } else {
        try {
            foreach ($backendIds as $backendId) {
                $backend = Mage::getSingleton('backend/backend')
                    ->load($backendId)
                    ->setStatus($this->getRequest()->getParam('status'))
                    ->setIsMassupdate(true)
                    ->save();
            }
            $this->_getSession()->addSuccess(
                $this->__('Total of %d record(s) were successfully updated', count($backendIds))
            );
        } catch (Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
    }
    $this->_redirect('*/*/index');
}

public function exportCsvAction()
{
    $fileName   = 'backend.csv';
    $content    = $this->getLayout()->createBlock('backend/adminhtml_content_grid')
        ->getCsv();

    $this->_sendUploadResponse($fileName, $content);
}

public function exportXmlAction()
{
    $fileName   = 'backend.xml';
    $content    = $this->getLayout()->createBlock('backend/adminhtml_content_grid')
        ->getXml();

    $this->_sendUploadResponse($fileName, $content);
}

protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
    $response = $this->getResponse();
    $response->setHeader('HTTP/1.1 200 OK','');
    $response->setHeader('Pragma', 'public', true);
    $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
    $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
    $response->setHeader('Last-Modified', date('r'));
    $response->setHeader('Accept-Ranges', 'bytes');
    $response->setHeader('Content-Length', strlen($content));
    $response->setHeader('Content-type', $contentType);
    $response->setBody($content);
    $response->sendResponse();
    die;
}
}